<template>
  <view class="components-list tn-safe-area-inset-bottom">
    <!-- <tn-nav-bar fixed :height=80 :customBack=true backgroundColor='tn-main-gradient-orangeyellow' fontColor="#FFFFFF"
      :bottomShadow=true>
      <view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
        <view><text class='tn-icon-left'></text></view>
        <view><text class='tn-icon-home-capsule-fill'></text></view>
      </view>
      <view class="custom-nav-content">
        <view class="search-content">

        </view>
      </view>
    </tn-nav-bar> -->


    <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
      疫苗
    </tn-nav-bar>
   



    <!-- 页面内容 -->
    <view>
      <view class="time-line__wrap">
        <tn-time-line>
          <block v-for="(items, index) in list" :key="index">
            <tn-time-line-item>
              <template slot="node"> 
                <view
                  :class="['time-line-item__node', { 'tn-main-gradient-orangeyellow': index  == currentMonth }]">
                  <view class="time-line-item__node--icon tn-icon tn-icon-success"></view>
                </view>
              </template>
              <template slot="content">
                <view class="sub-box" :id="`months-${index}`">
                  <tn-list-view :card="true" :customTitle="true" unlined="all">
                    <template slot="title">
                      <view class="custom-title tn-bg-grey--light">
                        <view style="width: 155rpx; height: 50rpx;margin-left: -30rpx; background-repeat: no-repeat;"
                          class="">
                          <text style="margin-left: 30rpx;color:black;"> {{ items.name }}</text>
                        </view>
                      </view>
                    </template>
                    <block v-for="(item, index_sub) in items.item" :key="index_sub">
                      <view>
                        <view class="">
                          <tn-list-cell class="custom-title">
                            <view>
                              <view class="vaccine-title-wrap" @click="showVaccineDetail(item)">
                                <view class="title-content">
                                  {{ item.title }} 
                                  <text class="tn-text-sm tn-color-gray tn-padding-left">{{ item.desc }}</text>
                                </view>
                                <text class="tn-icon-right arrow-icon"></text>
                              </view>
                              <view><text class="tn-icon-success-circle"
                                  :class="[item.data ? 'tn-color-teal' : 'tn-color-gray']"></text>
                                <text class="tn-color-gray">时间 <span class="tn-text-sm">{{ item.data ?
                                    item.data.createdAt : ""
                                    }}</span></text>
                              </view>
                              <view><text class="tn-icon-success-circle"
                                  :class="[item.data && item.data.is_remind ? 'tn-color-teal' : 'tn-color-gray']"></text><text
                                  class="tn-color-gray">提醒
                                </text></view>
                              <view><text class="tn-icon-success-circle"
                                  :class="[item.data && item.data.is_done ? 'tn-color-teal' : 'tn-color-gray']"></text><text
                                  class="tn-color-gray">完成
                                </text></view>
                            </view>
                            <tn-button :plain="true" class="tn-icon tn-icon-set  tn-border tn-border-orangeyellow"
                              style="margin-bottom: auto;" shape="round" @click="setPlan(item.id)">设置</tn-button>
                          </tn-list-cell>
                        </view>
                      </view>
                    </block>
                  </tn-list-view>
                </view>
                <view>
                  <view class="time-line-item__content__title"></view>

                  <view class="time-line-item__content__desc"></view>
                </view>
              </template>
            </tn-time-line-item>
          </block>
        </tn-time-line>
      </view>

    </view>
    <!-- popup -->
    <tn-popup v-model="show" mode="bottom" length="50%" :marginTop="vuex_custom_bar_height" backgroundColor="#FFFFFF"
      :width="width" :height="height" :borderRadius="borderRadius" :closeBtn="closeBtn" :closeBtnIcon="closeBtnIcon"
      :closeBtnPosition="closeBtnPosition" :maskCloseable="maskCloseable" @close="closedPopup">

      <view class="popup-content">
        <!-- 标题栏 -->
        <view class="popup-header">
          <text class="popup-title">疫苗计划设置</text>
        </view>

        <!-- 表单内容 -->
        <view class="form-item">
          <text class="label">计划时间</text>
          <view class="picker-value tn-bg-gray--light" @click="openPicker">
            <text>{{ formData.planDate || '请选择日期' }}</text>
            <text class="tn-icon-right"></text>
          </view>
        </view>

        <tn-picker v-model="showPicker" :params="timeParams" :defaultTime="formData.planDate" @confirm="onTimeConfirm"
          @cancel="onTimeCancel"></tn-picker>

        <view class="form-item">
          <text class="label">提醒通知</text>
          <view class="switch-wrapper">
            <text class="tn-icon-email icon-gradient"></text>
            <tn-switch v-model="formData.isRemind" activeColor="#FFCA28" inactiveColor="#EEEEEE"></tn-switch>
          </view>
        </view>

        <view class="form-item contact-selection" v-if="formData.isRemind">
          <text class="label">接收通知</text>
          <view class="contacts-list">
            <tn-checkbox-group v-model="formData.selectedContacts">
              <view class="checkbox-item" v-for="contact in contacts" :key="contact.id">
                <tn-checkbox :name="contact.id" :checked="formData.selectedContacts.includes(contact.id)"
                  color="tn-main-gradient-orangeyellow" activeColor="#FFCA28">
                  {{ contact.name }}
                </tn-checkbox>
              </view>
            </tn-checkbox-group>
          </view>
        </view>

        <view class="form-item">
          <text class="label">完成接种</text>
          <view class="switch-wrapper">
            <text class="tn-icon-check-circle icon-gradient"></text>
            <tn-switch v-model="formData.isDone" activeColor="#FFCA28" inactiveColor="#EEEEEE"></tn-switch>
          </view>
        </view>

        <!-- 底部按钮 -->
        <view class="form-actions">
          <tn-button @click="closedPopup" backgroundColor="#F5F5F5" fontColor="#333333"
            class="cancel-btn">取消</tn-button>
          <tn-button @click="savePlan" backgroundColor="tn-main-gradient-orangeyellow" class="save-btn">保存</tn-button>
        </view>
      </view>
    </tn-popup>
  </view>

</template>

<script>
import demoTitle from '@/libs/components/demo-title.vue'
import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
import { plan, planSet } from "@/api/plan.js";
import { mapState } from 'vuex';

export default {
  name: 'plan',
  mixins: [template_page_mixin],
  components: { demoTitle },
  data() {
    return {
      // 弹出层配置
      show: false,
      selectShow: false,
      mode: 'bottom',
      backgroundColor: '',
      width: '80%',
      height: '65%',
      borderRadius: 23,
      closeBtn: true,
      closeBtnIcon: '',
      closeBtnPosition: 'top-right',
      maskCloseable: true,
      type: 1,

      // 疫苗计划列表数据
      list: [
        { name: '出生', item: [{ id: 12, title: "卡介苗", desc: "第1针" }, { id: 13, title: "乙肝疫苗", desc: "第1针" }] },
        { name: '1月龄', item: [{ id: 1, title: "乙肝疫苗", desc: "第2针" }] },
        { name: '2月龄', item: [{ id: 3, title: "脊灰灭活疫苗", desc: "第1针" }] },
        { name: '3月龄', item: [{ id: 5, title: "脊灰灭活疫苗", desc: "第2针" }, { id: 2, title: "百白破疫苗", desc: "第1针" }] },
        { name: '4月龄', item: [{ id: 6, title: "百白破疫苗", desc: "第2针" }, { id: 7, title: "脊灰减毒活疫苗", desc: "第1针" }] },
        { name: '5月龄', item: [{ id: 8, title: "百白破疫苗", desc: "第3针" }] },
        { name: '6月龄', item: [{ id: 11, title: "乙肝疫苗", desc: "第3针" }] },
        { name: '8月龄', item: [{ id: 14, title: "麻腮风", desc: "第1针" }, { id: 15, title: "乙脑疫苗", desc: "第1针" }] },
        { name: '9月龄', item: [{ id: 16, title: "A群流脑多糖疫苗", desc: "第2针" }] },
        { name: '18月龄', item: [{ id: 18, title: "百白破疫苗", desc: "第4针" }, { id: 19, title: "麻腮风", desc: "第2针" }, { id: 19, title: "甲肝减毒活", desc: "第1针" }] },
        { name: '24月龄', item: [{ id: 19, title: "乙脑减毒活疫苗", desc: "第2针" }] },
        { name: '36月龄', item: [{ id: 20, title: "A群C群流脑多糖疫苗", desc: "第1针" }] },
        { name: '48月龄', item: [{ id: 21, title: "脊灰减毒活疫苗", desc: "第2针" }] },
        { name: '72月龄', item: [{ id: 22, title: "A群C群流脑多糖疫苗", desc: "第2针" }, { id: 23, title: "白破疫苗", desc: "第1针" }] },
      ],

      // 表单数据
      formData: {
        planDate: '',        // 计划接种日期
        isRemind: false,     // 是否需要提醒
        isDone: false,       // 是否已完成接种
        planId: null,        // 计划ID
        selectedContacts: [] // 选中的联系人ID列表
      },

      contacts: [], // 联系人列表
      showPicker: false,
      timeParams: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: false
      }
    }
  },
  computed: {
  ...mapState(['userInfo']),
  // 计算当前婴儿月龄
  currentMonth() {
    const birthDate = this.userInfo.birthday;

    // 检查 birthDate 是否有效
    if (!birthDate || isNaN(new Date(birthDate).getTime())) {
      return 0; // 如果无效，返回 0
    }

    const birth = new Date(birthDate);
    const today = new Date();

    let months = (today.getFullYear() - birth.getFullYear()) * 12;
    months += today.getMonth() - birth.getMonth();

    if (today.getDate() < birth.getDate()) {
      months--;
    }

    if (months == 7) {
      return 8;
    } else if (months > 9 && months <= 17) {
      return 9;
    } else if (months > 18 && months <= 23) {
      return 10;
    } else if (months > 24 && months <= 35) {
      return 11;
    } else if (months > 36 && months <= 47) {
      return 12;
    } else if (months > 48 && months <= 72) {
      return 13;
    }
    return months;
  },
},
  methods: {
       // 返回上一页
       goBack() {
      uni.navigateBack();
    },
    
    // 显示疫苗详情
    showVaccineDetail(item) {
      const vaccineData = {
        title: item.title,
        desc: item.desc,
        time: item.data ? item.data.createdAt : '',
        isDone: item.data ? !!item.data.is_done : false
      };
      
      uni.navigateTo({
        url: `/pages/vaccine/vaccine-detail?id=${item.id}&data=${encodeURIComponent(JSON.stringify(vaccineData))}`
      });
    },
    // 设置疫苗计划
    async setPlan(id) {
      this.formData.planId = id;
      this.contacts = this.userInfo.familys;

      const findInList = (predicate) => {
        return this.list.flatMap(month => month.item)
          .filter(Boolean)
          .find(predicate);
      };

      const planData = findInList(item => item.data?.plan_id === id)?.data;
      const planItem = findInList(item => item.id === id);


      // Initialize form data with default values
      this.formData = {
        planId: id,
        planDate: planData?.createdAt || '',
        isRemind: Boolean(planData?.is_remind),
        isDone: Boolean(planData?.is_done),
        planName: planItem?.title + ' ' + planItem?.desc || '',
        selectedContacts: planData?.familys?.map(family => (family.id)) || []
      };

      // Update contacts only if we have plan data
      if (planData?.familys) {
        const contactIds = new Set(planData.familys.map(family => family.id));
        this.contacts = this.userInfo.familys.map(contact => ({
          ...contact,
          checked: contactIds.has(contact.id)
        }));
      } else {
        this.contacts = this.userInfo.familys;
      }

      this.show = true;
    },

    closedPopup() {
      this.show = false
    },

    // 获取疫苗计划数据
    async getData() {
      try {
        const res = await plan({ type: this.type });
        if (!res) return;
        const dataMap = new Map(
          res.map(item => [item.plan_id, item])
        );
        this.list = this.list.map(listGroup => ({
          ...listGroup,
          item: listGroup.item.map(item => ({
            ...item,
            data: dataMap.get(item.id) || item.data
          }))
        }));
      } catch (error) {
        console.error('Error updating list data:', error);
      }

    },

    // 保存疫苗计划
    async savePlan() {
      if (!this.formData.planDate) {
        // 提示用户选择计划时间
        uni.showToast({
                        title: '请选择计划时间',
                        icon: 'none',
                        duration: 2000
                    });
        return;
      }

      this.formData.type = this.type
      await planSet(this.formData);
      this.show = false;
      this.getData()
    },
    openPicker() {
      this.showPicker = true
    },

    onTimeConfirm(event) {
      this.formData.planDate = `${event.year}-${event.month}-${event.day} ${event.hour + ':'}${event.minute}`
      this.showPicker = false
    },

    onTimeCancel() {
      this.showPicker = false
    }
  },
  // 生命周期钩子
  onShow() {
    this.getData();
  },
  mounted() {
    this.$nextTick(() => {
      const index = this.currentMonth;
      const query = uni.createSelectorQuery().in(this);

      // 选择目标元素
      query.select(`#months-${index}`).boundingClientRect();
      query.selectViewport().scrollOffset();

      query.exec((res) => {
        if (res[0] && res[1]) {
          // 获取目标元素的位置信息
          const elementRect = res[0];
          const viewportScrollOffset = res[1].scrollTop;

          // 计算滚动到目标位置
          const targetScrollTop = elementRect.top - 85 + viewportScrollOffset;

          // 滚动到目标位置
          uni.pageScrollTo({
            scrollTop: targetScrollTop,
            duration: 0, // 滚动动画时长，单位 ms
          });
        } else {
          console.error("Failed to find the target element or viewport");
        }
      });
    });


  },
}
</script>

<style lang="scss" scoped>
@import '@/static/css/templatePage/custom_nav_bar.scss';


span {
  margin-left: 20rpx;
}

.components-list {
  background-color: $tn-bg-gray-color;
  min-height: 100vh;
}

.custom-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx 20rpx;
}


.custom-nav-content {
  width: 80%;
  height: 100%;
  display: flex;
  align-items: center;
  margin-left: 20rpx;

  .search-content {
    flex: 1;

    .search-input {
      border-radius: 30rpx;

      /* #ifdef MP-WEIXIN */
      /deep/ .tn-input-class {
        border-radius: 30rpx;
      }

      /* #endif */
    }
  }
}

.time-line {

  &__wrap {
    margin-top: 50px;
    padding: 60rpx 30rpx 30rpx 60rpx;
  }

  &-item {
    &__node {
      width: 44rpx;
      height: 44rpx;
      border-radius: 100rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #AAAAAA;

      &--active {
        background-color: $tn-main-color;
      }

      &--icon {
        color: #FFFFFF;
        font-size: 24rpx;
      }
    }

    &__content {
      &__title {
        font-weight: bold;
        font-size: 32rpx;
      }

      &__desc {
        color: $tn-font-sub-color;
        font-size: 28rpx;
        margin-bottom: 6rpx;
      }

      &__time {
        color: $tn-font-holder-color;
        font-size: 26rpx;
      }
    }
  }
}

.popup-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 100%;
  padding: 30rpx;

  .popup-header {
    text-align: center;
    margin-bottom: 20rpx;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .form-item {
    margin-bottom: 20rpx;

    .label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
    }

    .picker-value {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 20rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333;

      .tn-icon-right {
        color: #999;
        font-size: 24rpx;
      }
    }

    .switch-wrapper {
      display: flex;
      align-items: center;
      gap: 10rpx;

      .icon-gradient {
        font-size: 36rpx;
        background: linear-gradient(45deg, #FF9700, #ED1C24);
        -webkit-background-clip: text;
        color: transparent;
      }

      :deep(.tn-switch__node) {
        background-color: #FFFFFF;
      }
    }

    &.contact-selection {
      .contacts-list {
        margin-top: 10rpx;
        display: flex;
        flex-wrap: wrap;
        gap: 10rpx;

        .checkbox-item {
          background-color: #F8F8F8;
          padding: 10rpx 20rpx;
          border-radius: 8rpx;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    gap: 15rpx;
    margin-top: 20rpx;

    .cancel-btn,
    .save-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;

      &::after {
        border: none;
      }
    }
  }
}

.contacts-list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;

  .checkbox-item {
    margin-right: 30rpx;
    margin-bottom: 20rpx;
  }
}
.vaccine-title-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15rpx;
  padding: 4rpx 0;
  
  .title-content {
    flex: 1;
    padding-right: 20rpx;
  }
  
  .arrow-icon {
    margin-left:20rpx ;
    color: #999;
    font-size: 32rpx;
    transition: transform 0.2s ease;
  }
  
  &:active {
    .arrow-icon {
      transform: translateX(6rpx);
      color: #FF9700;
    }
  }
}
</style>
